import React from 'react';
import { observer, inject } from 'mobx-react';
import * as _ from '../../util/public/common';
import WfForm_Public from '../../util/public/interface';
import * as Parse from '../../util/public/parseLayout';
import { getLabel } from '../../util/convert';

@observer
export default class InsertIframe extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            showIframe: false,
        }
    }

    sysFieldName ={requestname:"field-1",requestlevel:"field-2",signinput:"field-4",dycs:"field-9",mj:"field-10"};
    iframeParams = {
        set_id: "",
        set_name: "",
        set_src: "",
        set_style: {},
        temp_src: "", //用于存储未替换动态遍历的src
        dynamicFieldnames: [],  //动态改变的字段fieldname
        iframeAuto: {},  //自适应高度时用的参数
        loadHeight: {}  //loding的高度
    };
    setIframeParams =(data={})=>{
        const keys = Object.keys(data);
        keys.forEach(key => {
            this.iframeParams[key] = data[key];
        })
    }


    componentWillMount() {
        const {jsonparam, cellMark} = this.props;
        let set_id = jsonparam.set_id ? jsonparam.set_id : "";
        let set_name = jsonparam.set_name ? jsonparam.set_name : "";
        let set_src = jsonparam.set_src ? jsonparam.set_src : "";
        let set_height = jsonparam.set_height ? jsonparam.set_height : "";
        let set_style = jsonparam.set_style ? jsonparam.set_style : "";
        let height = {};
        if (set_height === "auto"||set_height==="") {
            height = {height: "0px"};
            this.setIframeParams({ loadHeight:{height: "100px", lineHeight: "100px"} });
            this.setIframeParams({ iframeAuto:{adjustheight: 'y', eachcount: 0} });
        } else {
            height = {height: set_height + "px"};
            this.setIframeParams({ loadHeight:{height: set_height + "px", lineHeight: set_height + "px"} });
        }
        let styleObj = this.analyzeStyle(set_style);
        let style = {width: "100%", ...height, ...styleObj};
        let src = this.analyzeField(set_src);

        this.setIframeParams({ set_src:src,set_id:set_id,set_name:set_name,set_style:style });
    }

    componentDidMount() {
        //console.log("-------------componentDidMount------------");
        const {temp_src,dynamicFieldnames} = this.iframeParams;

        let fieldstr = this.analyzeDynamicField(dynamicFieldnames);
        let iframeref = this.refs.insertiframe;
        //字段值改变时触发
        WfForm_Public.bindFieldChangeEvent(fieldstr, function (obj, id, value) {
            //console.log("WfForm.bindFieldChangeEvent--", obj, id, value);
            let src = Parse.getDynamicFieldValueSrc(dynamicFieldnames, temp_src);
            jQuery(iframeref).attr("src", src);
        });
    }

    //解析动态字段fieldname为fieldidstr
    analyzeDynamicField = (dynamicFieldnames)=>{
        let fieldarr = [];
        _.forEach(dynamicFieldnames, (value) =>{
            let repalceReg = '\\$\\[' + value + '\\]\\$';
            let fieldid = WfForm_Public.convertFieldNameToId(value);
            fieldarr.push(fieldid);
        });
        return fieldarr.join(',');
    }

    //解析字段
    analyzeField = (src) => {
        //常用参数
        const commonPara = ['requestid', 'workflowid', 'nodeid', 'formid']
        commonPara.map((item) => {
            let repalceReg = '\\$' + item + '\\$';
            src = src.replace(new RegExp(repalceReg, "gm"), WfForm_Public.getBaseInfo()[item]);
        })

        //匹配固定参数
        let patt = /\$[^(\$\=\[)]+\$/g;;
        let fixedFieldnames = src.match(patt);
        //需要去重
        fixedFieldnames = Array.from(new Set(fixedFieldnames));
        for (let i = 0; i < fixedFieldnames.length; i++) {
            let fieldname = fixedFieldnames[i];
            fieldname = fieldname.substr(0, fieldname.length - 1);
            fieldname = fieldname.substr(1, fieldname.length - 1);
            let fieldid = WfForm_Public.convertFieldNameToId(fieldname);
            //系统字段处理[requestname,requestlevel,signinput,dycs,mj]field-1  field-2  field-4  field-9   field-10
            if (this.sysFieldName[fieldname]&&fieldid===""){
                fieldid = this.sysFieldName[fieldname];
            }

            let repalceReg = '\\$' + fieldname + '\\$';
            src = src.replace(new RegExp(repalceReg, "gm"), WfForm_Public.getFieldValue(fieldid));
        }
        //保存替换过固定参数的src  动态参数改变时 基于此src 再次替换
        this.setIframeParams({ temp_src:src });

        //匹配动态参数 $[]$  绑定事件
        let reg = /[^\$\[\]]+(?=\])/g;
        let dynamicFieldnames = src.match(reg);
        //需要去重
        dynamicFieldnames = Array.from(new Set(dynamicFieldnames))
        this.setIframeParams({ dynamicFieldnames:dynamicFieldnames });
        //先替换一次动态参数
        src = Parse.getDynamicFieldValueSrc(dynamicFieldnames, src);

        //console.log("src=" + src)
        return src;
    }

    //解析style字符串为对象
    analyzeStyle = (style) => {
        if (style.trim().length == 0) {
            return {};
        }
        //先去掉所有空格
        style = style.replace(/\s+/g, "");
        //如果以;结尾 ->去掉
        if (this.confirmEnding(style, ";")) {
            style = style.substr(0, style.length - 1);
        }
        //拼接为json字符串
        style = '{' + style.replace(/;/g, ',') + '}';

        //console.log(style);
        //用双引号包括 key和value  不然解析不出来
        style = style.replace(/(?:\s*['"]*)?([a-zA-Z0-9_-]+)(?:['"]*\s*)?:/g, "\"$1\":");
        style = style.replace(/":/g, "\":\"").replace(/,"/g, "\",\"").replace(/}/g, "\"}");
        //console.log("jsonArr=" + JSON.parse(style));
        return JSON.parse(style);
    }

    //判断str是否以target结尾
    confirmEnding = (str, target) => {
        var start = str.length - target.length;
        var arr = str.substr(start, target.length);
        if (arr == target) {
            return true;
        }
        return false;
    }


    render() {
        const {showIframe} = this.state;
        const {set_id, set_name, set_style, set_src,loadHeight,iframeAuto} = this.iframeParams;
        let hideLodingStyle = showIframe ? {dispaly: "none"} : {};
        let hideIframeStyle = showIframe ? {} : {height: "0px"};


        return (
            <div>
                <div className="iframeLoading" style={{...loadHeight, ...hideLodingStyle}}><span><img
                    src="/images/loading2_wev8.gif" align="absmiddle"/></span><span>{getLabel(125516,"内容加载中，请稍候...")}</span></div>
                <iframe
                    src={set_src}
                    id={set_id}
                    name={set_name}
                    ref={"insertiframe"}
                    onLoad={() => {
                        this.setState({showIframe: true});
                        window.iframeOperate.loadingOver(this.refs.insertiframe);
                    }}

                    frameBorder="0"
                    scrolling="auto"
                    style={{...set_style, ...hideIframeStyle}}
                    {...iframeAuto}
                ></iframe>
            </div>
        )
    }
}